package cn.liuyi.weiyi;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.pku.tools.SharedPreferencesHelper;
import cn.edu.pku.tools.YJRApplication;
import cn.edu.pku.tools.YJRHttpClient;
import cn.yjr.fragment.FragmentFactory;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.manuelpeinado.fadingactionbar.extras.actionbarsherlock.FadingActionBarHelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.viewpagerindicator.TabPageIndicator;

/**
 * @author vector
 *
 */
public class DoctorPageActivity extends SherlockFragmentActivity implements OnClickListener{
	LayoutInflater inflater;
	ActionBar actionBar;
	View title_bar;
	Context context;
	String response;
	JSONObject jsonInfo;
	JSONObject doctor;
	SharedPreferencesHelper spHelper;
	ImageView bjy_imv;
	ViewPager mPager;
	TabPageIndicator indicator;
	String id = null;
	String name =null;
	String hospital = null;
	String head = null;
	String category = null;
	String section = null;
	String title = null;
	String title_name = null;
	boolean recommend = false;
	String notice, skills, type;
	LinearLayout fqzx_ll, tjbjy_ll, sqjh_ll;
	TextView bjy_tv;
	View head_view;
	String groupIntro;
	private static final String[] CONTENT = new String[] { "基本资料","业务公告","众筹项目"};
	int currIndex = 2;
	int height = 0;
	int statusBarHeight;
	DisplayImageOptions options;
	TextView doctor_info_tv, doctor_name_tv;
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	 @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        
	        FadingActionBarHelper helper = new FadingActionBarHelper()
	            .actionBarBackground(R.drawable.home_bg)
	            .headerLayout(R.layout.doctor_page_action_bar)
	            .contentLayout(R.layout.activity_doctor_page);
	        setContentView(helper.createView(this));
	        head_view = helper. returnHeaderView();
	        Intent intent = this.getIntent();
	        String doc = intent.getStringExtra("doctor");
	        try {
				doctor = new JSONObject(doc);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        //setContentView(R.layout.activity_doctor_page);
	        inflater = this.getLayoutInflater();
			actionBar = getSupportActionBar();
			//initTitleBar();
			context = this;
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.me_jobinfo)
			.showImageForEmptyUri(R.drawable.me_appointment)
			.showImageOnFail(R.drawable.head)
			.cacheInMemory(true)
			.cacheOnDisc(true)
			.considerExifParams(true)
			.displayer(new RoundedBitmapDisplayer(100))//是否设置为圆角，弧度为多少  
			.bitmapConfig(Bitmap.Config.RGB_565)
			.build();
			WindowManager wm = (WindowManager) this.getWindowManager();
			height = wm.getDefaultDisplay().getHeight();
			statusBarHeight = getStatusHeight(this);
			this.spHelper = new SharedPreferencesHelper(this.context);
			
			
	        helper.initActionBar(this);
	        
			initData();
			initComponent();
			
			initEventListener();
			
			
			
		
		}
		
	 	private void initData(){
	 		try {
				name = doctor.getString("name");
				hospital = doctor.getJSONObject("hospital").getString("text");
				head = doctor.getString("avatar");
				category = doctor.getString("category");
				recommend = doctor.getBoolean("recommend");
				section = doctor.getJSONObject("section").getString("text");
				groupIntro = doctor.getString("groupIntro");
				title = doctor.getString("title");
				notice = doctor.getString("notice");
				skills = doctor.getString("skills");
				type = doctor.getString("type");
				id = doctor.getString("id");
				//title_name = YJRApplication.initData.getJSONObject("codings").getJSONObject("doctoryCategory").getJSONObject(category).getJSONObject("title").getString(title);
				title_name = YJRApplication.initData.getJSONObject("codings").getJSONObject("doctorCategory").getJSONObject(category).getJSONObject("title").getString(title);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	 	}

		private void initTitleBar(){
			ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,ActionBar.LayoutParams.WRAP_CONTENT,Gravity.CENTER);
			title_bar = inflater.inflate(R.layout.account_action_bar, null);
			
			actionBar.setCustomView(title_bar,lp);
			actionBar.setDisplayShowHomeEnabled(false);
			actionBar.setDisplayShowTitleEnabled(false);
			actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
			actionBar.setDisplayShowCustomEnabled(true);
		}
		private void initComponent(){
			fqzx_ll = (LinearLayout) findViewById(R.id.fqzx_ll);
			tjbjy_ll = (LinearLayout) findViewById(R.id.tjbjy_ll);
			sqjh_ll = (LinearLayout) findViewById(R.id.sqjh_ll);
			bjy_tv = (TextView) findViewById(R.id.bjy_tv);
			doctor_info_tv = (TextView) head_view.findViewById(R.id.doctor_info_tv);
		    doctor_name_tv = (TextView) head_view.findViewById(R.id.doctor_name_tv);
		    bjy_imv = (ImageView) findViewById(R.id.bjy_imv);
			initViewPager();
			indicator = (TabPageIndicator)findViewById(R.id.indicator);
	        indicator.setViewPager(mPager);
	        mPager.setCurrentItem(1);
	        doctor_info_tv.setText(hospital + " " + section + " " + title_name);
	        doctor_name_tv.setText(name + " 医生");
	        
	        checkIsFav();
		}
		
		private void initEventListener(){
			fqzx_ll.setOnClickListener(this);
			tjbjy_ll.setOnClickListener(this);
			sqjh_ll.setOnClickListener(this);
			
		}

		@SuppressLint("NewApi")
		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.fqzx_ll:
				Intent intent = new Intent(DoctorPageActivity.this, StartChatActivity.class);
				intent.putExtra("doctor", doctor.toString());
				startActivity(intent);
				break;
			case R.id.tjbjy_ll:
				addFav();
				break;
			case R.id.sqjh_ll:
				break;
			default:
					break;
			}
			
		}
		
		private void initViewPager(){
			mPager = (ViewPager) findViewById(R.id.pager_);
			
//			
//			final LinearLayout ll_ = (LinearLayout) findViewById(R.id.header_ll);
//			int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
//	        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
//	        ll_.measure(w, h);
//	        
//	        final LinearLayout ll = (LinearLayout) findViewById(R.id.pager_parent_ll);
//			final android.view.ViewGroup.LayoutParams params = ll.getLayoutParams();
//	        
//	        ViewTreeObserver vto = ll_.getViewTreeObserver();
//			vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
//	            public boolean onPreDraw() {
//	            	//Toast.makeText(context, statusBarHeight + "dp", Toast.LENGTH_SHORT).show();
//	            	params.height = height - ll_.getMeasuredHeight() - actionBar.getHeight() -statusBarHeight;
//	    			
//	    		    ll.setLayoutParams(params);
//	                return true;
//	            }
//	        });
			mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
			
			
		}
		class MyPagerAdapter extends FragmentPagerAdapter{

			/**
			 * @param fm
			 */
			public MyPagerAdapter(FragmentManager fm) {
				super(fm);
			}

			@Override
			public Fragment getItem(int arg0) {
				return FragmentFactory.getInstanceByIndex(arg0 + 5, doctor);
			}
			
			@Override
	        public CharSequence getPageTitle(int position) {
	            return CONTENT[position % CONTENT.length];
	        }

			@Override
			public int getCount() {
				return CONTENT.length;
			}
			
		}
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		      switch (requestCode) {
		      default:  
		          break;  

		      }  
		      super.onActivityResult(requestCode, resultCode, data);  
		  }  

	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	    	getSupportMenuInflater().inflate(R.menu.activity_test_menu, menu);
	        return true;
	    }
	    
	    
	    /**
	     * 
	     * @param activity
	     * @return > 0 success; <= 0 fail
	     */
	    public int getStatusHeight(Activity activity){
	        int statusHeight = 0;
	        Rect localRect = new Rect();
	        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
	        statusHeight = localRect.top;
	        if (0 == statusHeight){
	            Class<?> localClass;
	            try {
	                localClass = Class.forName("com.android.internal.R$dimen");
	                Object localObject = localClass.newInstance();
	                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
	                statusHeight = activity.getResources().getDimensionPixelSize(i5);
	            } catch (ClassNotFoundException e) {
	                e.printStackTrace();
	            } catch (IllegalAccessException e) {
	                e.printStackTrace();
	            } catch (InstantiationException e) {
	                e.printStackTrace();
	            } catch (NumberFormatException e) {
	                e.printStackTrace();
	            } catch (IllegalArgumentException e) {
	                e.printStackTrace();
	            } catch (SecurityException e) {
	                e.printStackTrace();
	            } catch (NoSuchFieldException e) {
	                e.printStackTrace();
	            }
	        }
	        return statusHeight;
	    }
	    
	    private void checkIsFav() {
	    	
	    	RequestParams params = new RequestParams(); 
	    	params.add("doctorId", id);
	    	YJRHttpClient.post(context,"/patient/isFav", params, new JsonHttpResponseHandler(){
	    		 @Override  
	                public void onSuccess(JSONObject data) {  
	                 	jsonInfo = data;
	                 	try {
	    					if(jsonInfo.getInt("result") == 1){
	    						YJRHttpClient.setCookie(context); 
	    						if(jsonInfo.getBoolean("response")==true){
	    							bjy_tv.setText("已添加为保健医");
	    							bjy_imv.setImageResource(R.drawable.docinfo_favorited);
	    						}else{
	    							bjy_tv.setText("添加为保健医");
	    							bjy_imv.setImageResource(R.drawable.docinfo_addfavorite);
	    						}
	    					}else{
	    						Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
	    					}
	    				} catch (JSONException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	                }  
	    	});
	    	
	    }
	    
	    private void addFav() {
	    	
	    	RequestParams params = new RequestParams(); 
	    	params.add("doctorId", id);
	    	YJRHttpClient.post(context,"/patient/addFav", params, new JsonHttpResponseHandler(){
	    		 @Override  
	                public void onSuccess(JSONObject data) {  
	                 	jsonInfo = data;
	                 	try {
	    					if(jsonInfo.getInt("result") == 1){
	    						YJRHttpClient.setCookie(context); 
	    						
	    						Toast.makeText(context, "添加保健医成功", Toast.LENGTH_SHORT).show();
	    						bjy_tv.setText("已添加为保健医");
	    						bjy_imv.setImageResource(R.drawable.docinfo_favorited);
	    					}else{
	    						Toast.makeText(context, jsonInfo.getString("info"), Toast.LENGTH_SHORT).show();
	    					}
	    				} catch (JSONException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	                }  
	    	});
	    	
	    }
}
